package com.echo.yixiaowu.feature.main.home

import android.app.Application
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.echo.yixiaowu.feature.main.home.repository.SortDataRepository
import com.echo.yixiaowu.feature.player.FetchBackendDataUiState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class HomeViewModel(application: Application) : AndroidViewModel(application) {
    private val CACHE_DURATION_MS = 10 * 60 * 1000L
    private val repository = SortDataRepository(application)
    private val _sortState = MutableStateFlow(SortState())
    val sortState = _sortState.asStateFlow()

    private val _recommendState = MutableStateFlow(RecommendState())
    val recommendState = _recommendState.asStateFlow()

    private val _effect = Channel<SortEffect>()
    val effect = _effect.receiveAsFlow()

    init {
        loadInitialData()
    }

    fun onEvent(event: HomeEvent) {
        when (event) {
            is HomeEvent.OnSaveChanges -> saveOrder(event.menuItems)
            is HomeEvent.OnItemSelected -> itemSelected(event.itemId)
            is HomeEvent.OnTabSelected -> tabSelected(event.pageId, event.tabId)
            is HomeEvent.OnLoadTabData -> loadTabData(
                event.userId,
                event.tabId,
                event.isUserExecute
            )
        }
    }

    // 根据userId + tabId 加载个性数据
    private fun loadTabData(userId: Int, tabId: Int, isUserExecute: Boolean) {
        viewModelScope.launch {
            val recommendState = recommendState.value
            val now = System.currentTimeMillis()
            val timeSinceLastFetch =
                now - recommendState.fetchBackendDataUiState.lastFetchedTimestamp
            if (isUserExecute || recommendState.recommendList.isEmpty() || timeSinceLastFetch > CACHE_DURATION_MS) {
                _recommendState.update {
                    it.copy(
                        fetchBackendDataUiState = FetchBackendDataUiState(
                            isLoading = true
                        )
                    )
                }
                val recommendData = fetchRecommendData(userId)
                _recommendState.update {
                    it.copy(
                        recommendList = recommendData,
                        fetchBackendDataUiState = FetchBackendDataUiState(
                            false, null, now
                        )
                    )
                }
            }
        }
    }

    private fun tabSelected(pageId: Int, tabId: Int) {
        _sortState.update {
            it.copy(
                items = it.items.map { item ->
                    if (item.id == pageId) {
                        item.copy(tabSelectedPage = tabId)
                    } else {
                        item
                    }
                }
            )
        }
    }

    private fun itemSelected(itemId: Int) {
        _sortState.update {
            it.copy(
                selectedItemId = itemId,
                items = it.items.map { item ->
                    item.copy(isSelect = item.id == itemId)
                })
        }
    }

    private fun loadInitialData() {
        viewModelScope.launch {
            repository.clearOrder()
            val initialItems = repository.saveOrderFlow.first()
            _sortState.update { it ->
                it.copy(
                    items = initialItems,
                    isLoading = false,
                    selectedItemId = initialItems.first { it.isSelect }.id,

                    // 基于加载的 initialItems 创建状态
                    listStates = List(initialItems.size) { LazyListState() },
                    innerGridStates = initialItems.associate { item ->
                        item.id to List(item.tabs.size) { LazyStaggeredGridState() }
                    }.toMutableMap(),
                )
            }
        }
    }

    private fun saveOrder(newItems: List<DraggableItem>) {
        viewModelScope.launch {
            _sortState.update { it.copy(items = newItems) }
            repository.saveOrder(newItems)
            _effect.send(SortEffect.ShowToast("保存成功"))
        }
    }
}

suspend fun fetchRecommendData(userId: Int): List<RecommendItem> {
    delay(100)
    return List(9) { index ->
        val userName = if (index % 2 == 0) "Alice" else "Bob"
        val userDetail = if (index % 2 == 0) "欢迎用户$userId Alice's detail" else "Bob's detail"
        if (index % 5 == 0) {
            RecommendItem(
                id = index.toString(),
                userName = userName,
                userDetail = userDetail,
                userAvatar = "11",
                type = "recommend",
                url = listOf(
                    "https://gips2.baidu.com/it/u=2560577328,2450090727&fm=3042&app=3042&f=JPEG&wm=1,baiduai,0,0,13,9&wmo=0,0&w=512&h=512",
                    "https://i1.hdslb.com/bfs/archive/cda28259d08951a8682ab383b4d56ebe8f9e117d.jpg",
                    "https://i1.hdslb.com/bfs/archive/9d7b51f8490082c81c1b7db8e46f61ec5eb6bd46.jpg"
                ),
                description = "霓虹闪烁，车水马龙，谱写着都市的繁华乐章。这张图片的描述会稍微长一些，用于测试文字换行对高度的影响。"
            )
        } else if (index % 2 == 0) {
            RecommendItem(
                id = index.toString(),
                userName = userName,
                userDetail = userDetail,
                userAvatar = "11",
                type = "recommend",
                url = listOf(
                    "https://i1.hdslb.com/bfs/archive/cda28259d08951a8682ab383b4d56ebe8f9e117d.jpg",
                    "https://i1.hdslb.com/bfs/archive/9d7b51f8490082c81c1b7db8e46f61ec5eb6bd46.jpg"
                ),
                description = "巍峨的山峰，云雾缭绕，仿佛置身仙境。"
            )
        } else {
            RecommendItem(
                id = index.toString(),
                userName = userName,
                userDetail = userDetail,
                userAvatar = "11",
                type = "recommend",
                url = listOf("https://gips2.baidu.com/it/u=2560577328,2450090727&fm=3042&app=3042&f=JPEG&wm=1,baiduai,0,0,13,9&wmo=0,0&w=512&h=512"),
                description = "KMP on iOS 深度工程化：模块化、并发编译与 98% 增量构建加速"
            )
        }
    }
}
